"use client"

import { useState, useEffect } from 'react'
import { getPlayers, deletePlayer, getRegions } from '@/lib/data'
import { Player, Region } from '@/types/player'
import { 
  Card, 
  CardContent, 
  CardDescription, 
  CardHeader, 
  CardTitle 
} from '@/components/ui/card'
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from '@/components/ui/table'
import { 
  DropdownMenu, 
  DropdownMenuContent, 
  DropdownMenuItem, 
  DropdownMenuSeparator, 
  DropdownMenuTrigger 
} from '@/components/ui/dropdown-menu'
import { 
  AlertDialog, 
  AlertDialogAction, 
  AlertDialogCancel, 
  AlertDialogContent, 
  AlertDialogDescription, 
  AlertDialogFooter, 
  AlertDialogHeader, 
  AlertDialogTitle 
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useToast } from '@/components/ui/use-toast'
import { Checkbox } from '@/components/ui/checkbox'
import AddPlayerForm from '@/components/admin/add-player-form'
import EditPlayerModal from '@/components/admin/edit-player-modal'
import { 
  Search, 
  Trash2, 
  MoreVertical, 
  Edit, 
  Plus, 
  Medal, 
  Ban, 
  Filter,
  ChevronDown,
  CheckCircle,
  XCircle,
  RefreshCw
} from 'lucide-react'

interface PlayersManagerProps {
  onPlayersUpdate?: (players: Player[]) => void;
}

export default function PlayersManager({ onPlayersUpdate }: PlayersManagerProps) {
  const [players, setPlayers] = useState<Player[]>([])
  const [filteredPlayers, setFilteredPlayers] = useState<Player[]>([])
  const [regions, setRegions] = useState<Region[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showAddForm, setShowAddForm] = useState(false)
  const [editingPlayer, setEditingPlayer] = useState<Player | null>(null)
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [playerToDelete, setPlayerToDelete] = useState<Player | null>(null)
  const [selectedPlayers, setSelectedPlayers] = useState<string[]>([])
  const [searchQuery, setSearchQuery] = useState('')
  const [regionFilter, setRegionFilter] = useState('all')
  const [tierFilter, setTierFilter] = useState('all')
  const [statusFilter, setStatusFilter] = useState('all')
  const [isRefreshing, setIsRefreshing] = useState(false)
  const { toast } = useToast()

  // 加载玩家数据
  const loadData = async () => {
    try {
      setIsRefreshing(true)
      setError(null)
      
      // 并行加载数据
      const [playersData, regionsData] = await Promise.all([
        getPlayers(),
        getRegions()
      ])
      
      setPlayers(playersData)
      
      // 如果有onPlayersUpdate回调，将数据传递给父组件
      if (onPlayersUpdate) {
        onPlayersUpdate(playersData)
      }
      
      setRegions(regionsData)
      
      // 应用过滤器
      applyFilters(playersData, searchQuery, regionFilter, tierFilter, statusFilter)
      
      // 清空选中
      setSelectedPlayers([])
    } catch (err: any) {
      console.error('加载玩家数据失败:', err)
      setError('无法加载玩家数据，请稍后重试')
      toast({
        variant: "destructive",
        title: "加载失败",
        description: "获取玩家数据时发生错误，请重试",
      })
    } finally {
      setLoading(false)
      setIsRefreshing(false)
    }
  }

  useEffect(() => {
    loadData()
  }, [])

  // 应用所有过滤器
  const applyFilters = (
    data: Player[],
    query: string,
    region: string,
    tier: string,
    status: string
  ) => {
    let result = [...data]
    
    // 搜索过滤
    if (query) {
      const lowercasedQuery = query.toLowerCase()
      result = result.filter(
        player => player.name.toLowerCase().includes(lowercasedQuery) || 
                  player.id.toString().includes(lowercasedQuery)
      )
    }
    
    // 地区过滤
    if (region && region !== 'all') {
      result = result.filter(player => player.region === region)
    }
    
    // 段位过滤
    if (tier && tier !== 'all') {
      if (tier === 'none') {
        result = result.filter(player => !player.best_tier_name)
      } else {
        result = result.filter(player => player.best_tier_name === tier)
      }
    }
    
    // 状态过滤
    if (status && status !== 'all') {
      if (status === 'blacklisted') {
        result = result.filter(player => player.is_blacklisted)
      } else if (status === 'active') {
        result = result.filter(player => !player.is_blacklisted)
      }
    }
    
    setFilteredPlayers(result)
  }

  // 当过滤条件变化时应用过滤器
  useEffect(() => {
    if (players.length > 0) {
      applyFilters(players, searchQuery, regionFilter, tierFilter, statusFilter)
    }
  }, [players, searchQuery, regionFilter, tierFilter, statusFilter])

  // 处理添加玩家成功
  const handleAddPlayerSuccess = () => {
    setShowAddForm(false)
    loadData()
    toast({
      title: "添加成功",
      description: "玩家已成功添加到系统",
    })
  }

  // 处理编辑玩家成功
  const handleUpdatePlayerSuccess = () => {
    setEditingPlayer(null)
    loadData()
    toast({
      title: "更新成功",
      description: "玩家信息已成功更新",
    })
  }

  // 打开删除对话框
  const handleOpenDeleteDialog = (player: Player) => {
    setPlayerToDelete(player)
    setDeleteDialogOpen(true)
  }

  // 删除玩家
  const handleDeletePlayer = async () => {
    if (!playerToDelete) return
    
    try {
      await deletePlayer(playerToDelete.id)
      setDeleteDialogOpen(false)
      setPlayerToDelete(null)
      
      // 刷新数据
      loadData()
      
      toast({
        title: "删除成功",
        description: `玩家 "${playerToDelete.name}" 已成功删除`,
      })
    } catch (err: any) {
      console.error('删除玩家失败:', err)
      toast({
        variant: "destructive",
        title: "删除失败",
        description: "无法删除该玩家，请稍后重试",
      })
    }
  }

  // 处理选择玩家
  const handleSelectPlayer = (playerId: string) => {
    setSelectedPlayers(prev => {
      if (prev.includes(playerId)) {
        return prev.filter(id => id !== playerId)
      } else {
        return [...prev, playerId]
      }
    })
  }

  // 全选/取消全选
  const handleSelectAll = () => {
    if (selectedPlayers.length === filteredPlayers.length) {
      setSelectedPlayers([])
    } else {
      setSelectedPlayers(filteredPlayers.map(player => player.id))
    }
  }

  // 从搜索列表中获取唯一的段位名称
  const getTierOptions = () => {
    const uniqueTiers = new Set<string>()
    players.forEach(player => {
      if (player.best_tier_name) {
        uniqueTiers.add(player.best_tier_name)
      }
    })
    return Array.from(uniqueTiers).sort()
  }

  if (loading && !isRefreshing) {
    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <Skeleton className="h-8 w-36" />
          <Skeleton className="h-10 w-28" />
        </div>
        
        <div className="flex flex-col sm:flex-row gap-4 mb-4">
          <Skeleton className="h-10 flex-1" />
          <Skeleton className="h-10 w-40" />
          <Skeleton className="h-10 w-40" />
        </div>
        
        <div className="border rounded-md">
          <div className="h-10 border-b px-4 flex items-center">
            <Skeleton className="h-4 w-full" />
          </div>
          {[1, 2, 3, 4, 5].map((i) => (
            <div key={i} className="flex items-center space-x-4 p-4 border-b">
              <Skeleton className="h-4 w-4" />
              <Skeleton className="h-12 w-12 rounded-full" />
              <div className="space-y-2 flex-1">
                <Skeleton className="h-4 w-[250px]" />
                <Skeleton className="h-4 w-[200px]" />
              </div>
              <Skeleton className="h-8 w-20" />
            </div>
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <h2 className="text-2xl font-bold tracking-tight">玩家管理</h2>
        
        <div className="flex items-center gap-2 self-end sm:self-auto">
          <Button 
            variant="outline" 
            size="sm"
            onClick={loadData}
            disabled={isRefreshing}
            className="flex items-center gap-2"
          >
            <RefreshCw className={`h-4 w-4 ${isRefreshing ? 'animate-spin' : ''}`} />
            {isRefreshing ? '刷新中...' : '刷新'}
          </Button>
          
          <Button onClick={() => setShowAddForm(true)} className="flex items-center gap-2">
            <Plus className="h-4 w-4" />
            添加玩家
          </Button>
        </div>
      </div>
      
      {error && (
        <div className="p-4 rounded-lg bg-red-950 border border-red-800 text-red-200">
          <div className="flex items-center gap-2 mb-2">
            <XCircle className="h-5 w-5" />
            <h3 className="font-semibold">错误</h3>
          </div>
          <p>{error}</p>
        </div>
      )}
      
      <Card className="border border-gray-800 bg-[#1a1d24]">
        <CardHeader className="pb-3">
          <CardTitle>玩家列表</CardTitle>
          <CardDescription>
            管理玩家信息、段位和权限
            {filteredPlayers.length > 0 && (
              <span className="ml-2 text-blue-400">
                {filteredPlayers.length} 个玩家
                {filteredPlayers.length !== players.length && ` (共 ${players.length} 个)`}
              </span>
            )}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {/* 搜索和过滤UI */}
          <div className="flex flex-col sm:flex-row gap-4 mb-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-3 h-4 w-4 text-gray-500" />
              <Input
                placeholder="搜索玩家名称或ID..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9 bg-[#252a33] border-gray-700"
              />
            </div>
            
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" className="flex items-center gap-2 w-full sm:w-auto">
                  <Filter className="h-4 w-4" />
                  地区
                  <ChevronDown className="h-4 w-4 ml-2" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="w-56 bg-[#252a33] border-gray-700">
                <DropdownMenuItem 
                  onClick={() => setRegionFilter('all')}
                  className={regionFilter === 'all' ? 'bg-blue-900/20 text-blue-400' : ''}
                >
                  所有地区
                  {regionFilter === 'all' && <CheckCircle className="h-4 w-4 ml-auto" />}
                </DropdownMenuItem>
                
                <DropdownMenuSeparator className="bg-gray-700" />
                
                {regions.map(region => (
                  <DropdownMenuItem 
                    key={region.id}
                    onClick={() => setRegionFilter(region.name)}
                    className={regionFilter === region.name ? 'bg-blue-900/20 text-blue-400' : ''}
                  >
                    <div className="flex items-center gap-2">
                      <div
                        className="w-3 h-3 rounded-full"
                        style={{ backgroundColor: region.color }}
                      ></div>
                      {region.name}
                    </div>
                    {regionFilter === region.name && <CheckCircle className="h-4 w-4 ml-auto" />}
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>
            
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" className="flex items-center gap-2 w-full sm:w-auto">
                  <Medal className="h-4 w-4" />
                  段位
                  <ChevronDown className="h-4 w-4 ml-2" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="w-56 bg-[#252a33] border-gray-700">
                <DropdownMenuItem 
                  onClick={() => setTierFilter('all')}
                  className={tierFilter === 'all' ? 'bg-blue-900/20 text-blue-400' : ''}
                >
                  所有段位
                  {tierFilter === 'all' && <CheckCircle className="h-4 w-4 ml-auto" />}
                </DropdownMenuItem>
                
                <DropdownMenuItem 
                  onClick={() => setTierFilter('none')}
                  className={tierFilter === 'none' ? 'bg-blue-900/20 text-blue-400' : ''}
                >
                  无段位
                  {tierFilter === 'none' && <CheckCircle className="h-4 w-4 ml-auto" />}
                </DropdownMenuItem>
                
                <DropdownMenuSeparator className="bg-gray-700" />
                
                {getTierOptions().map(tier => (
                  <DropdownMenuItem 
                    key={tier}
                    onClick={() => setTierFilter(tier)}
                    className={tierFilter === tier ? 'bg-blue-900/20 text-blue-400' : ''}
                  >
                    {tier}
                    {tierFilter === tier && <CheckCircle className="h-4 w-4 ml-auto" />}
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>
            
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" className="flex items-center gap-2 w-full sm:w-auto">
                  <Ban className="h-4 w-4" />
                  状态
                  <ChevronDown className="h-4 w-4 ml-2" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="w-56 bg-[#252a33] border-gray-700">
                <DropdownMenuItem 
                  onClick={() => setStatusFilter('all')}
                  className={statusFilter === 'all' ? 'bg-blue-900/20 text-blue-400' : ''}
                >
                  所有状态
                  {statusFilter === 'all' && <CheckCircle className="h-4 w-4 ml-auto" />}
                </DropdownMenuItem>
                
                <DropdownMenuSeparator className="bg-gray-700" />
                
                <DropdownMenuItem 
                  onClick={() => setStatusFilter('active')}
                  className={statusFilter === 'active' ? 'bg-blue-900/20 text-blue-400' : ''}
                >
                  <div className="flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-green-500"></div>
                    正常
                  </div>
                  {statusFilter === 'active' && <CheckCircle className="h-4 w-4 ml-auto" />}
                </DropdownMenuItem>
                
                <DropdownMenuItem 
                  onClick={() => setStatusFilter('blacklisted')}
                  className={statusFilter === 'blacklisted' ? 'bg-blue-900/20 text-blue-400' : ''}
                >
                  <div className="flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-red-500"></div>
                    黑名单
                  </div>
                  {statusFilter === 'blacklisted' && <CheckCircle className="h-4 w-4 ml-auto" />}
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
          
          {filteredPlayers.length === 0 ? (
            <div className="text-center py-10 bg-gray-950/50 rounded-lg border border-gray-800">
              <div className="flex flex-col items-center justify-center space-y-3">
                <Search className="h-10 w-10 text-gray-500" />
                <h3 className="text-lg font-medium text-gray-300">未找到匹配的玩家</h3>
                <p className="text-sm text-gray-500 max-w-md">
                  尝试使用不同的搜索词或调整过滤条件
                </p>
                <Button 
                  variant="outline" 
                  onClick={() => {
                    setSearchQuery('')
                    setRegionFilter('all')
                    setTierFilter('all')
                    setStatusFilter('all')
                  }}
                  className="mt-2"
                >
                  清除所有过滤器
                </Button>
              </div>
            </div>
          ) : (
            <div className="border border-gray-700 rounded-lg overflow-hidden">
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader className="bg-gray-900/50">
                    <TableRow>
                      <TableHead className="w-12">
                        <Checkbox 
                          checked={
                            filteredPlayers.length > 0 && 
                            selectedPlayers.length === filteredPlayers.length
                          }
                          onCheckedChange={handleSelectAll}
                          aria-label="选择所有"
                          className="translate-y-[2px]"
                        />
                      </TableHead>
                      <TableHead>基本信息</TableHead>
                      <TableHead>地区</TableHead>
                      <TableHead>段位</TableHead>
                      <TableHead>分数</TableHead>
                      <TableHead>状态</TableHead>
                      <TableHead className="text-right">操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredPlayers.map((player) => (
                      <TableRow 
                        key={player.id} 
                        className={`${
                          selectedPlayers.includes(player.id) 
                            ? 'bg-blue-950/20' 
                            : player.is_blacklisted 
                              ? 'bg-red-950/10'
                              : ''
                        } hover:bg-gray-800/50 transition-colors`}
                      >
                        <TableCell>
                          <Checkbox 
                            checked={selectedPlayers.includes(player.id)}
                            onCheckedChange={() => handleSelectPlayer(player.id)}
                            aria-label={`选择 ${player.name}`}
                          />
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center space-x-3">
                            <div className="w-10 h-10 rounded-full overflow-hidden border border-gray-700">
                              <img 
                                src={player.avatar || '/placeholder-user.jpg'} 
                                alt={player.name}
                                className="w-full h-full object-cover"
                                onError={(e) => { 
                                  (e.target as HTMLImageElement).src = '/placeholder-user.jpg';
                                  (e.target as HTMLImageElement).onerror = null;
                                }}
                              />
                            </div>
                            <div>
                              <div className="font-medium mb-1">{player.name}</div>
                              <div className="text-xs text-gray-400">{player.id}</div>
                            </div>
                          </div>
                        </TableCell>
                        <TableCell>
                          {player.region ? (
                            <div className="flex items-center gap-2">
                              <div 
                                className="w-3 h-3 rounded-full" 
                                style={{ backgroundColor: player.region_color || '#888' }}
                              ></div>
                              <span>{player.region}</span>
                            </div>
                          ) : (
                            <span className="text-gray-500">-</span>
                          )}
                        </TableCell>
                        <TableCell>
                          {player.best_tier_name ? (
                            <Badge 
                              variant="outline" 
                              className="bg-[#252a33] hover:bg-[#2d3441] border-gray-700"
                            >
                              {player.best_tier_name}
                            </Badge>
                          ) : (
                            <span className="text-gray-500">-</span>
                          )}
                        </TableCell>
                        <TableCell>
                          <div className="font-mono">
                            {player.score !== undefined ? player.score : 0}
                          </div>
                        </TableCell>
                        <TableCell>
                          {player.is_blacklisted ? (
                            <Badge variant="destructive" className="bg-red-950 hover:bg-red-900 text-red-300">
                              已拉黑
                            </Badge>
                          ) : (
                            <Badge variant="outline" className="bg-green-950 text-green-300 hover:bg-green-900 border-green-800">
                              正常
                            </Badge>
                          )}
                        </TableCell>
                        <TableCell className="text-right">
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon" className="h-8 w-8">
                                <MoreVertical className="h-4 w-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end" className="bg-[#252a33] border-gray-700">
                              <DropdownMenuItem 
                                onClick={() => setEditingPlayer(player)}
                                className="flex items-center gap-2"
                              >
                                <Edit className="h-4 w-4" />
                                编辑信息
                              </DropdownMenuItem>
                              <DropdownMenuItem 
                                className="flex items-center gap-2"
                              >
                                <Medal className="h-4 w-4" />
                                段位管理
                              </DropdownMenuItem>
                              <DropdownMenuSeparator className="bg-gray-700" />
                              <DropdownMenuItem 
                                onClick={() => handleOpenDeleteDialog(player)}
                                className="text-red-500 hover:text-red-400 flex items-center gap-2"
                              >
                                <Trash2 className="h-4 w-4" />
                                删除玩家
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
      
      {/* 添加玩家表单 */}
      {showAddForm && (
        <AddPlayerForm 
          onClose={() => setShowAddForm(false)} 
          onSuccess={handleAddPlayerSuccess} 
        />
      )}

      {/* 编辑玩家表单 */}
      {editingPlayer && (
        <EditPlayerModal
          player={editingPlayer}
          onClose={() => setEditingPlayer(null)}
          onSuccess={handleUpdatePlayerSuccess}
        />
      )}

      {/* 删除确认对话框 */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent className="bg-[#1a1d24] border-gray-800 text-white">
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除玩家?</AlertDialogTitle>
            <AlertDialogDescription className="text-gray-400">
              您确定要删除玩家 "{playerToDelete?.name}" 吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel className="bg-transparent border-gray-700 hover:bg-gray-800 hover:text-white">
              取消
            </AlertDialogCancel>
            <AlertDialogAction 
              onClick={handleDeletePlayer}
              className="bg-red-600 hover:bg-red-700 text-white focus:ring-red-600"
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
} 